package com.haier.service;

import com.haier.dao.classRoom.ClassRoomDao;
import com.haier.dao.student.StudentDao;
import com.haier.pojo.ClassRoom;
import com.haier.pojo.Student;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;

@Service
public class StudentServiceImpl implements StudentService {


    @Resource
    private PlatformTransactionManager transactionManager;

    @Resource
    private ClassRoomDao classRoomDao;

    @Resource
    private StudentDao studentDao;
    @Override
    public Student selectStudent(Integer id) {
        return studentDao.selectStudent(id);
    }

    /**
     * 读写 数据源  分布式事务 测试
     * @param student
     * @return
     */
    @Override
//    @Transactional
    public Integer insertStudent(Student student) {
        TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
        ClassRoom classRoom = new ClassRoom();
        classRoom.setName(student.getName());
        try {
            int s1 =  studentDao.insertStudent(student);
            int s =   classRoomDao.insClassRoom(classRoom);
            Integer a = 0;
            Integer b= 10;
            System.out.println(b/a);
        transactionManager.commit(transactionStatus);
            return s1;
        }catch (Exception e){
            System.out.println(e );
        transactionManager.rollback(transactionStatus);
        }
        return null;
    }

    /***
     * 读写数据源 单一事务测试
     */
//    @Override
//    public Integer insertStudent(Student student) {
//        TransactionStatus transactionStatus = studentDataSourceTransactionManager.getTransaction(new DefaultTransactionDefinition());
//        try {
//            int s1 =  studentDao.insertStudent(student);
//            Integer a = 0;
//            Integer b= 10;
//            System.out.println(b/a);
//            studentDataSourceTransactionManager.commit(transactionStatus);
//            return s1;
//        }catch (Exception e){
//            System.out.println(e );
//            studentDataSourceTransactionManager.rollback(transactionStatus);
//        }
//
//        return null;
//    }
}
